"""
数据库假数据填充脚本
"""
import asyncio
from datetime import datetime, timedelta
from sqlalchemy.orm import Session
from app.core.database import SessionLocal, engine
from app.models import Base
from app.models.user import User
from app.models.role import Role
from app.models.permission import Permission
from app.models.chat import ChatSession, ChatMessage
from app.models.release import Release, ReleaseLog, DeploymentConfig
from app.models.analytics import UserBehavior, PageView, UserSession
from app.core.security import get_password_hash
import random
import uuid

def create_fake_data():
    """创建假数据"""
    db = SessionLocal()
    
    try:
        # 创建所有表
        Base.metadata.create_all(bind=engine)
        
        # 1. 创建权限数据
        permissions = [
            Permission(name="user:read", description="查看用户"),
            Permission(name="user:write", description="编辑用户"),
            Permission(name="user:delete", description="删除用户"),
            Permission(name="chat:read", description="查看聊天"),
            Permission(name="chat:write", description="管理聊天"),
            Permission(name="release:read", description="查看发布"),
            Permission(name="release:write", description="管理发布"),
            Permission(name="analytics:read", description="查看分析"),
            Permission(name="system:admin", description="系统管理"),
        ]
        
        for perm in permissions:
            existing = db.query(Permission).filter(Permission.name == perm.name).first()
            if not existing:
                db.add(perm)
        
        db.commit()
        
        # 2. 创建角色数据
        roles_data = [
            {"name": "超级管理员", "description": "系统超级管理员", "permissions": ["system:admin", "user:read", "user:write", "user:delete", "chat:read", "chat:write", "release:read", "release:write", "analytics:read"]},
            {"name": "管理员", "description": "系统管理员", "permissions": ["user:read", "user:write", "chat:read", "chat:write", "release:read", "release:write", "analytics:read"]},
            {"name": "运维人员", "description": "运维管理人员", "permissions": ["release:read", "release:write", "analytics:read"]},
            {"name": "普通用户", "description": "普通用户", "permissions": ["chat:read", "analytics:read"]},
        ]
        
        for role_data in roles_data:
            existing_role = db.query(Role).filter(Role.name == role_data["name"]).first()
            if not existing_role:
                role = Role(name=role_data["name"], description=role_data["description"])
                db.add(role)
                db.commit()
                
                # 添加角色权限
                for perm_name in role_data["permissions"]:
                    permission = db.query(Permission).filter(Permission.name == perm_name).first()
                    if permission:
                        role.permissions.append(permission)
                
                db.commit()
        
        # 3. 创建用户数据
        users_data = [
            {"username": "admin", "email": "admin@company.com", "full_name": "系统管理员", "role": "超级管理员"},
            {"username": "manager", "email": "manager@company.com", "full_name": "项目经理", "role": "管理员"},
            {"username": "devops", "email": "devops@company.com", "full_name": "运维工程师", "role": "运维人员"},
            {"username": "user1", "email": "user1@company.com", "full_name": "张三", "role": "普通用户"},
            {"username": "user2", "email": "user2@company.com", "full_name": "李四", "role": "普通用户"},
            {"username": "user3", "email": "user3@company.com", "full_name": "王五", "role": "普通用户"},
        ]
        
        created_users = []
        for user_data in users_data:
            existing_user = db.query(User).filter(User.username == user_data["username"]).first()
            if not existing_user:
                role = db.query(Role).filter(Role.name == user_data["role"]).first()
                user = User(
                    username=user_data["username"],
                    email=user_data["email"],
                    full_name=user_data["full_name"],
                    hashed_password=get_password_hash("123456"),  # 默认密码
                    is_active=True,
                    avatar=f"https://api.dicebear.com/7.x/avataaars/svg?seed={user_data['username']}"
                )
                if role:
                    user.roles.append(role)
                db.add(user)
                created_users.append(user)
        
        db.commit()
        
        # 获取所有用户
        all_users = db.query(User).all()
        
        # 4. 创建聊天会话数据
        chat_sessions = []
        for i in range(20):
            user = random.choice(all_users)
            session = ChatSession(
                session_id=str(uuid.uuid4()),
                user_id=user.id,
                title=f"AI助手对话 {i+1}",
                created_at=datetime.now() - timedelta(days=random.randint(0, 30)),
                updated_at=datetime.now() - timedelta(hours=random.randint(0, 24)),
                meta_data={"model": "gpt-3.5-turbo", "temperature": 0.7}
            )
            db.add(session)
            chat_sessions.append(session)
        
        db.commit()
        
        # 5. 创建聊天消息数据
        for session in chat_sessions:
            message_count = random.randint(3, 15)
            for j in range(message_count):
                # 用户消息
                user_msg = ChatMessage(
                    session_id=session.id,
                    role="user",
                    content=f"这是用户的第{j+1}条消息，请问关于{random.choice(['产品功能', '技术问题', '业务流程', '系统使用'])}的问题",
                    created_at=session.created_at + timedelta(minutes=j*2),
                    meta_data={"type": "text"}
                )
                db.add(user_msg)
                
                # AI回复
                ai_msg = ChatMessage(
                    session_id=session.id,
                    role="assistant",
                    content=f"感谢您的提问！关于{random.choice(['产品功能', '技术问题', '业务流程', '系统使用'])}，我为您详细解答...",
                    created_at=session.created_at + timedelta(minutes=j*2+1),
                    meta_data={"type": "text", "model": "gpt-3.5-turbo"}
                )
                db.add(ai_msg)
        
        db.commit()
        
        # 6. 创建发布数据
        releases = []
        for i in range(15):
            release = Release(
                version=f"v{random.randint(1,3)}.{random.randint(0,9)}.{random.randint(0,9)}",
                title=f"版本发布 {i+1}",
                description=f"这是第{i+1}个版本的发布说明，包含了新功能和bug修复",
                status=random.choice(["pending", "in_progress", "completed", "failed"]),
                environment=random.choice(["development", "staging", "production"]),
                created_by=random.choice(all_users).id,
                created_at=datetime.now() - timedelta(days=random.randint(0, 60)),
                scheduled_at=datetime.now() + timedelta(days=random.randint(1, 30)),
                meta_data={
                    "branch": f"release/v{random.randint(1,3)}.{random.randint(0,9)}.{random.randint(0,9)}",
                    "commit": f"abc{random.randint(1000,9999)}",
                    "features": [f"功能{j+1}" for j in range(random.randint(2,5))]
                }
            )
            db.add(release)
            releases.append(release)
        
        db.commit()
        
        # 7. 创建发布日志数据
        for release in releases:
            log_count = random.randint(3, 8)
            for j in range(log_count):
                log = ReleaseLog(
                    release_id=release.id,
                    level=random.choice(["info", "warning", "error"]),
                    message=f"发布步骤{j+1}: {random.choice(['代码检查通过', '构建成功', '测试完成', '部署启动', '健康检查'])}",
                    created_at=release.created_at + timedelta(minutes=j*5),
                    meta_data={"step": f"step_{j+1}", "duration": random.randint(10, 300)}
                )
                db.add(log)
        
        db.commit()
        
        # 8. 创建部署配置数据
        configs = [
            {"name": "生产环境", "environment": "production", "replicas": 3},
            {"name": "测试环境", "environment": "staging", "replicas": 2},
            {"name": "开发环境", "environment": "development", "replicas": 1},
        ]
        
        for config_data in configs:
            config = DeploymentConfig(
                name=config_data["name"],
                environment=config_data["environment"],
                config={
                    "replicas": config_data["replicas"],
                    "resources": {"cpu": "500m", "memory": "512Mi"},
                    "env_vars": {"NODE_ENV": config_data["environment"]},
                    "health_check": {"path": "/health", "port": 8000}
                },
                is_active=True,
                created_by=all_users[0].id,
                created_at=datetime.now() - timedelta(days=random.randint(1, 10))
            )
            db.add(config)
        
        db.commit()
        
        # 9. 创建用户行为数据
        for _ in range(500):
            behavior = UserBehavior(
                user_id=random.choice(all_users).id,
                action=random.choice(["login", "logout", "view_page", "click_button", "submit_form", "download_file"]),
                resource=random.choice(["dashboard", "chat", "release", "analytics", "profile", "settings"]),
                created_at=datetime.now() - timedelta(days=random.randint(0, 30), hours=random.randint(0, 23)),
                meta_data={
                    "ip": f"192.168.1.{random.randint(1, 255)}",
                    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                    "duration": random.randint(1, 300)
                }
            )
            db.add(behavior)
        
        # 10. 创建页面访问数据
        pages = ["dashboard", "chat", "release", "analytics", "profile", "settings", "login"]
        for _ in range(1000):
            page_view = PageView(
                user_id=random.choice(all_users).id if random.random() > 0.1 else None,  # 10%匿名访问
                page=random.choice(pages),
                url=f"/{random.choice(pages)}",
                referrer=f"/{random.choice(pages)}" if random.random() > 0.3 else None,
                created_at=datetime.now() - timedelta(days=random.randint(0, 30), hours=random.randint(0, 23)),
                meta_data={
                    "ip": f"192.168.1.{random.randint(1, 255)}",
                    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                    "load_time": random.randint(100, 3000)
                }
            )
            db.add(page_view)
        
        # 11. 创建用户会话数据
        for _ in range(200):
            user_session = UserSession(
                user_id=random.choice(all_users).id,
                session_id=str(uuid.uuid4()),
                started_at=datetime.now() - timedelta(days=random.randint(0, 30), hours=random.randint(0, 23)),
                ended_at=datetime.now() - timedelta(days=random.randint(0, 30), hours=random.randint(0, 22)),
                duration=random.randint(60, 7200),  # 1分钟到2小时
                page_views=random.randint(1, 50),
                meta_data={
                    "ip": f"192.168.1.{random.randint(1, 255)}",
                    "device": random.choice(["desktop", "mobile", "tablet"]),
                    "browser": random.choice(["Chrome", "Firefox", "Safari", "Edge"])
                }
            )
            db.add(user_session)
        
        db.commit()
        
        print("✅ 假数据创建成功！")
        print(f"📊 创建了以下数据：")
        print(f"   - 权限: {len(permissions)} 个")
        print(f"   - 角色: {len(roles_data)} 个")
        print(f"   - 用户: {len(users_data)} 个")
        print(f"   - 聊天会话: {len(chat_sessions)} 个")
        print(f"   - 发布版本: {len(releases)} 个")
        print(f"   - 部署配置: {len(configs)} 个")
        print(f"   - 用户行为: 500 条")
        print(f"   - 页面访问: 1000 条")
        print(f"   - 用户会话: 200 条")
        
        # 显示默认用户信息
        print("\n🔑 默认用户账号（密码都是: 123456）：")
        for user_data in users_data:
            print(f"   - {user_data['username']} ({user_data['full_name']}) - {user_data['role']}")
        
    except Exception as e:
        print(f"❌ 创建假数据失败: {e}")
        db.rollback()
    finally:
        db.close()

if __name__ == "__main__":
    create_fake_data()